package com.mijie.homi.service.user;

import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mijie.core.ApplicationProperties;
import com.mijie.homi.dao.user.IDBoxDao;
import com.mijie.homi.domain.user.IDBox;

@Service
public class IDBoxService {

	@Autowired
	private IDBoxDao dao;
	
	private static final int DEFAULT_FETCH_ID_SIZE = 2000;
	private int fetchIdSize = -1;
	
	private List<IDBox> idsCache = null;
	private int cacheIndex = 0;
	private ReadWriteLock accessDBLock = new ReentrantReadWriteLock();
	
	private  List<IDBox> getIds(){
		if(idsCache==null || idsCache.isEmpty()){
			if(fetchIdSize==-1){
				String value = ApplicationProperties.get("idboxservice.fetch.id.size");
				fetchIdSize = DEFAULT_FETCH_ID_SIZE;
				if(value!=null) fetchIdSize = Integer.parseInt(value);
			}
			Lock lock = accessDBLock.readLock();
			try{
				lock.lock();
				idsCache = dao.getIds(fetchIdSize);
			}finally{
				if(lock!=null) lock.unlock();
			}
		}
		return idsCache;
	}
	
	protected synchronized IDBox getFreeId(){
		List<IDBox> ids = getIds();
		IDBox box = null;
		if(!ids.isEmpty()){
			box = ids.get(cacheIndex++);
			if(cacheIndex==fetchIdSize){
				cacheIndex = 0;
				idsCache.clear();
			}
		}
		return box;
	}
	
	public int removeIDBox(IDBox box){
		int succ =  0;
		Lock lock = accessDBLock.writeLock();
		try{
			lock.lock();
			succ = dao.removeIDBox(box);
		}finally{
			if(lock!=null) lock.unlock();
		}
		return succ;
	}
	
}
